package com.starryx.driverschool.service.impl;

import com.starryx.driverschool.dao.TrainRepository;
import com.starryx.driverschool.po.Train;
import com.starryx.driverschool.service.TrainService;
import com.starryx.driverschool.vo.TrainQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class TrainServiceImpl implements TrainService {

    @Autowired
    private TrainRepository trainRepository;

    @Override
    public List<Train> listTrain() {
        return trainRepository.findAll();
    }

    @Override
    public Page<Train> listTrain(Pageable pageable) {
        return trainRepository.findAll(pageable);
    }

    @Override
    public Page<Train> listTrain(Pageable pageable, TrainQuery trainQuery) {
        return trainRepository.findAll(new Specification<Train>() {
            @Override
            public Predicate toPredicate(Root<Train> root,       // 相当于表名
                                         CriteriaQuery<?> cq,   // 条件查询执行器
                                         CriteriaBuilder cb) {  // 条件语句构建器，用于定义查询条件
                List<Predicate> predicates = new ArrayList<>();     // 查询条件组
                if (!"".equals(trainQuery.getName()) && trainQuery.getName() != null) {
                    predicates.add(cb.like(root.<String>get("student").<String>get("name"), "%" + trainQuery.getName() + "%"));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));     // 将条件构造器构建的查询条件放到执行器执行
                return null;
            }
        }, pageable);
    }

    @Transactional
    @Override
    public Train saveTrain(Train train) {
        return trainRepository.save(train);
    }

    @Override
    public Train getTrain(Long id) {
        return trainRepository.findOne(id);
    }

    @Transactional
    @Override
    public void deleteTrain(Long id) {
        trainRepository.delete(id);
    }
}
